//
//  iFarmaciaAppDelegate.m
//  iFarmacia
//
//  Created by Jose Lino on 12/8/10.
//  Copyright 2010 Skymedia. All rights reserved.
//

#import "iFarmaciaAppDelegate.h"


@implementation iFarmaciaAppDelegate

@synthesize window;
@synthesize tabBarController;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    // Nome do banco de dados
	databaseName = @"farm_05.sql";
	
	
	// Obter o caminho para o diretório de documentos e acrescente o databaseName
	NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDir = [documentPaths objectAtIndex:0];
	databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
	
    // Override point for customization after application launch.

    // Add the tab bar controller's view to the window and display.
    [self.window addSubview:tabBarController.view];
    [self.window makeKeyAndVisible];
	self.window.backgroundColor = [UIColor clearColor];
	[self checkAndCreateDatabase];

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark UITabBarControllerDelegate methods

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}
*/

/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/


#pragma mark -
#pragma mark Funções para Banco de Dados

-(void) checkAndCreateDatabase{
	// Verifique se o banco de dados SQL já tenha sido salvo para os usuários do telefone, se não, então copie-o
	BOOL success;
	
	// Cria um objeto FileManager, vamos usar isso para verificar o status
	// do banco de dados e copie-o se necessário
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	// Verifique se o banco de dados já foi criada nos usuários do sistema de arquivos
	success = [fileManager fileExistsAtPath:databasePath];
	
	// Se o banco de dados já existe, em seguida, voltar sem fazer nada
	if(success){
		NSLog(@"O banco ja existe");
		return;
	}else {
		NSLog(@"Novo Banco Criad: %@", databaseName);
	}
	
	// Se não, então é para copiar o banco de dados do aplicativo para os usuários do sistema de arquivos
	// Obter o caminho para o banco de dados no pacote de aplicativos
	NSLog(@"Copiar banco para o sistema");
	NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
	
	// Copie o banco de dados do pacote para os usurios do sistema de arquivos
	[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
    [tabBarController release];
    [window release];
    [super dealloc];
}

@end

